package com.think.db.mongo;

import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.think.db.mongo.domain.DatabaseCounter;
import dev.morphia.Datastore;
import dev.morphia.Morphia;
import dev.morphia.config.MorphiaConfig;
import dev.morphia.query.filters.Filters;

public final class DatabaseManager {
    private static Datastore gameDatastore;

    public static Datastore getGameDatastore() {
        return gameDatastore;
    }

    public static MongoDatabase getGameDatabase() {
        return gameDatastore.getDatabase();
    }

    public static void initialize(String connectionUrl) {
        // 加载自定义配置文件
        var config = MorphiaConfig.load("morphia-config.properties");

        // 创建 MongoDB 客户端
        var client = MongoClients.create(connectionUrl);

        // 使用加载的配置创建 Datastore
        gameDatastore = Morphia.createDatastore(client, config);
    }

    public static synchronized int getNextId(Class<?> c) {
        DatabaseCounter counter =
                getGameDatastore()
                        .find(DatabaseCounter.class)
                        .filter(Filters.eq("_id", c.getSimpleName()))
                        .first();

        if (counter == null) {
            counter = new DatabaseCounter(c.getSimpleName());
        }

        try {
            return counter.getNextId();
        } finally {
            DatabaseHelper.saveGameAsync(counter);
        }
    }

    public static synchronized int getNextId(Object o) {
        return getNextId(o.getClass());
    }
}
